package api

import (
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"net/http"
	"strconv"
)

type CreateUserReq struct {
	Name string `json:"name"`
	Addr string `json:"addr"`
}

type GetUserReq struct {
	ID float64 `json:"id"`
}

type UpdateUserReq struct {
	ID float64 `json:"id"`
	Name string `json:"name"`
	Addr string `json:"addr"`
}

type DeleteUserReq struct {
	ID int64 `json:"id"`
}

type UserRes struct {
	ID int64 `json:"id"`
	Name string `json:"name"`
	Addr string `json:"addr"`
}

func (u *UserApi)CreateUser(ctx *gin.Context) {
	//request body -> DTO
	r := &CreateUserReq{}
	err := ctx.BindJSON(r)
	if err != nil {
		ctx.Set("errors", err)
		return
	}

	//调用业务逻辑
	res, err := u.us.CreateUser(ctx, r)
	if err != nil {
		ctx.Set("errors", err)
		return
	}

	//DTO->res body
	ctx.JSON(http.StatusOK, res)
}

func (u *UserApi)GetUser(ctx *gin.Context) {
	//request body -> DTO
	r := &GetUserReq{}
	uID := ctx.Query("id")
	if uID == "" {
		ctx.Set("errors", errors.New("params id is required"))
		return
	}
	ID, _ := strconv.Atoi(uID)
	r.ID = float64(ID)
	//调用业务逻辑
	res, err := u.us.GetUser(ctx, r)
	if err != nil {
		ctx.Set("errors", err)
		return
	}

	//DTO->res body
	ctx.JSON(http.StatusOK, res)
}

func (u *UserApi)UpdateUser(ctx *gin.Context) {
	//request body -> DTO
	r := &UpdateUserReq{}
	err := ctx.BindJSON(r)
	if err != nil {
		ctx.Set("errors", err)
		return
	}

	//调用业务逻辑
	res, err := u.us.UpdateUser(ctx, r)
	if err != nil {
		ctx.Set("errors", err)
		return
	}

	//DTO->res body
	ctx.JSON(http.StatusOK, res)
}

func (u *UserApi)DeleteUser(ctx *gin.Context) {
	//request body -> DTO
	r := &DeleteUserReq{}
	err := ctx.BindJSON(r)
	if err != nil {
		ctx.Set("errors", err)
		return
	}

	//调用业务逻辑
	res, err := u.us.DeleteUser(ctx, r)
	if err != nil {
		ctx.Set("errors", err)
		return
	}

	//DTO->res body
	ctx.JSON(http.StatusOK, res)
}


